"""
-*- coding:utf-8 -*-
最终版web自动化
Author: Free
DataTime: 2020/7/17 11:56

"""

import hashlib
import base64


def md5_value(key):
    """
    :param key: 需要加密的内容
    :return: 进行md5加密的结果
    """
    input_name = hashlib.md5()
    input_name.update(key.encode("utf-8"))
    return input_name.hexdigest()


try:
    from Crypto.Cipher import AES
    from Crypto.Util.Padding import pad, unpad
except ImportError:
    print('请安装加解密库pycryptodome')


class AesSample(object):
    def __init__(self):
        self.key = '7DJgTLRZ17WLTm18'.encode('utf-8')
        self.iv = 'JZqrMKbMk5H6ewER'.encode('utf-8')
        self.mode = AES.MODE_CBC

    def encode(self, data):
        cipher = AES.new(self.key, self.mode, self.iv)
        pad_pkcs7 = pad(data.encode('utf-8'), AES.block_size, style='pkcs7')
        result = base64.encodebytes(cipher.encrypt(pad_pkcs7))
        encrypted_text = str(result, encoding='utf-8').replace('\n', '')
        return encrypted_text

    def decode(self, data):
        cipher = AES.new(self.key, self.mode, self.iv)
        base64_decrypted = base64.decodebytes(data.encode('utf-8'))
        una_pkcs7 = unpad(cipher.decrypt(base64_decrypted), AES.block_size, style='pkcs7')
        decrypted_text = str(una_pkcs7, encoding='utf-8')
        return decrypted_text

    def test(self):
        data1 = 'hello world!'
        data2 = '2qPsRxjBCSymGoMXKUu3EIg4ne4L0Xf8VDlfF2bYxbAIGbZoTfEdWDFjhqf1+HG+BPJti+vHdCvIdp3+LmTYEffPLhB3FlhnKQITXMv3vkbVJ3YNKV4oFsCud8zbbfZEyQEKY5XDiyfX+GZqgboVHtqujuuG4Emcvtuc7PP4/mWRDBzcUGCPI8qhiXZyaLRu'
        print('加密结果：', self.encode(data1))
        print('解密结果：', self.decode(data2))


if __name__ == '__main__':
    blog = AesSample()
    blog.test()
